<?php
	namespace app\index\controller;

	use \think\Db;

	class Login extends Base{

		// 登录提交处理
		public function index(){
			try{
				if($_POST){
					$user=input('post.user');

				if($user==''){
					$this->json(['msg'=>'请输入您的用户名','code'=>0]);
				}

				$pass=input('post.pass');

				if($pass==''){
					$this->json(['msg'=>'请输入您的密码','code'=>0]);
				}

				$row=Db::name('user')->field('u_id,u_username,u_icon,u_userpwd')->where(['u_username'=>$user])->find();

				if($row && $row['u_userpwd']==md5($pass)){

					// $token='zmy6666';

					$token=md5($row['u_id'].$row['u_username'].time().$this->key).$this->key;

					$res=Db::name('user')->where(['u_id'=>$row['u_id']])->update(['u_lastIp'=>$_SERVER['REMOTE_ADDR'],'u_lastTime'=>time()]);

					// 更新用户最后一次登录时间和ip

					$this->checkLogin($row,$token);

					$this->json(['msg'=>'','code'=>1,'token'=>$token]);

				}



				$this->json(['msg'=>'账号或密码不正确','code'=>0]);
			}else{
				echo '拒绝访问';
			}

			}catch(\Exception $e){
				return $this->err($e);
			}
		}


		// 验证登录信息
		public function authLogin(){
			try{
				if($_SERVER['REQUEST_METHOD']=='POST'){

					$token=$this->token;

					$user=(bool)input('post.user');

					if(empty($token) || !$row=$this->redis->hgetall($token) ){

						if($token){

							//token存在已过期
							$data=['code'=>-1,'msg'=>''];

						}else{

							// 没有token验证失败
							$data=['code'=>0,'msg'=>''];
						}

						return $this->json($data);
					}


					//验证成功
					$data=['code'=>1,'msg'=>''];

					$tokenTime=$this->redis->ttl($token);//获取token剩余的有效时间

					/*
						判断token超过了一定时间,且未过期,就重新生成token(保证了token的安全性)
					 */
					if($tokenTime+3600*2<$this->time){

						$newToken=$this->setToken($token);

						$data['code']=2;

						$data['token']=$newToken;

					}

					// 判断是否需要输出用户信息
					if($user){

						$data['info']=['user'=>$row['u_username'],'icon'=>$row['u_icon']];
					}

					return $this->json($data);
				}else{
					echo '拒绝访问';
				}
			}catch(\Exception $e){
				return  $this->err($e);
			}
		}

		/*
			$arr:需要存入的用户信息

			将用户信息存入redis,并且将之前没有过期的登录信息，给删除掉，防止多个端口登录
		 */
		private function checkLogin($arr=[],$token=''){

			$row=$this->redis->get('user:'.$arr['u_id']);

			$time=$this->time;


			if($row){
				$this->redis->del($row);
			}

			$this->redis->setex('user:'.$arr['u_id'],$time,$token);

			$this->redis->hmset($token,$arr);

			$this->redis->Expire($token,$time);
		}

		// 为用户的token延时(重新定义用户的token)
		private function setToken($token=''){

			$row=$this->redis->hgetall($token);

			if(!$row){
				return false;
			}

			$newToken=md5($row['u_id'].$row['u_username'].time().$this->key).$this->key;
			// 生成新的token

			$this->redis->setex('user:'.$row['u_id'],$this->time,$newToken);

			$this->redis->Expire($token,10);

			$this->redis->hmset($newToken,$row);

			$this->redis->Expire($newToken,$this->time);

			return $newToken;

		}

	}
?>